<?php  if (!defined('BASEPATH')) exit('No direct script access allowed');

class Parse extends CI_Controller {
	
	function __construct() {
		parent::__construct();
	}
	
	function index($sid){
		$this->load->library("session_manager");
		$sm = $this->session_manager;
		$this->load->database();
		$this->load->model("Gps_log_source");
		
		$data = array(
			"title" => "Parse - Parse Data",
			"jsarray" => array("resources/js/parse.js"),
			"extra" => ''
		);
		
		//输出HTML表单
		$this->load->view("header", $data);

		$data = array("nickname" => $sm->user['nickname']);
		$this->load->view("menu", $data);
		
		
		
		$source = $this->Gps_log_source->get_source_file($sm->user['uid'],$sid);
		if ($source) //存在文件记录
		{
			//分析数据中的数据段落
			$filename =  str_replace('//','/', $this->_build_path($sm->user['uid'], $source->upload_time, 'src'))."/".$source->filename;
			if (file_exists( $filename))
			{
				$sf = @fopen($filename,'r');
				if ($sf)
				{
					//读取数据
					$data = array();
					$count = 0;
					while (!feof($sf)) {
						$buffer = fgets($sf);
						//只有合法数据才被读取
						if (preg_match(
							'/20(\d{2})-([0|1][0-9])-([0-3][0-9]),([0-2][0-9]):([0-5][0-9]):([0-5][0-9])/',
							substr($buffer,0,19)
						))
						{
							$data[$count] = explode(',',$buffer);
							$count++;
						}
					    }
					fclose($sf);
					
					//分析数据段落
					$section = array();
					$oldtime = 0;
					$oldlat = 0;
					$oldlon = 0;
					$s = 0;
					$start=true;
					
					for ($count = 0; $count < count($data); $count++)
					{
						$t = @strtotime($data[$count][0]." ".$data[$count][1]);
						
						if ($start) //为一个时间段的开始
						{
							$section[$s]['starttime'] = $t;
							$section[$s]['startline'] = $count;
							$start = false;
						}
						
						//非第一次，且时间间隔超过5分钟或者经纬度差异0.005度
						if ($oldtime != 0 &&(abs($t-$oldtime)>300 || abs($data[$count][3]-$oldlat > 0.005) || abs($data[$count][4]-$oldlon > 0.005)))
						{
							$section[$s]['endtime'] = $t;
							$section[$s]['endline'] = $count;
							$start = true;
							$s++;
						}
						$oldtime = $t;
						if (isset($data[$count][3])) $oldlat = $data[$count][3];
						if (isset($data[$count][4])) $oldlon = $data[$count][4];
					}
					if (!$start) //最后一段的结尾
					{
						$section[$s]['endtime'] = $oldtime;
						$section[$s]['endline'] = $count-1;
					}
				}
			}
			
			$data = array("shortname" => $source->description,
				      "sid" => $sid,
				      "section" => $section
				      );
			$this->load->view("parse", $data);
		}	
		$this->load->view("footer");
		

	}
	
	function parse_file() {
		$this->load->library("session_manager");
		$sm = $this->session_manager;
		$this->load->library("gps");
		
		set_time_limit(UPLOAD_EXEC_TIME);
		
		//获取POST数据
		$shortname	= addslashes(trim($this->input->post("shortname","")));
		$description	= addslashes(trim($this->input->post("description","")));
		$sid		= $this->input->post("sid",0);
		$startline	= $this->input->post("startline",-1);
		$endline	= $this->input->post("endline",-1);
		
		
		//数据库操作
		$this->load->database();
		$this->load->model("Gps_log_source");
		$this->load->model("Gps_log_files");
		
		//数据库存储
		$source = $this->Gps_log_source->get_source_file($sm->user['uid'],$sid);
		if ($source) //存在文件记录
		{
			$filename =  str_replace('//','/', $this->_build_path($sm->user['uid'], $source->upload_time, 'src'))."/".$source->filename;
			if (file_exists( $filename))
			{
				$sf = @fopen($filename,'r');
				if ($sf)
				{
					//读取数据文件到数组
					$data = array();
					$count = 0;
					while (!feof($sf)) {
						$buffer = fgets($sf);
						//只有合法数据才被读取
						if (preg_match(
							'/20(\d{2})-([0|1][0-9])-([0-3][0-9]),([0-2][0-9]):([0-5][0-9]):([0-5][0-9])/',
							substr($buffer,0,19)
						))
						{
							$data[$count] = explode(',',$buffer);
							$count++;
						}
					    }
					fclose($sf);
				}
				
				//KML文件参数
				$gen_time = time();
				$kfn = $gen_time."_".md5($source->filename);
				$kml = str_replace('//','/', $this->_build_path($sm->user['uid'], $gen_time, 'kml'))."/".$kfn.".kml";
						   
				$kf = @fopen($kml, 'w');
				if ($kf)
				{
					fwrite($kf,
'<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2">
  <Document>
    <name>'.$shortname.'</name>
    <description>'.$description.'</description>
    <Style id="greenLineGreenPoly">
      <LineStyle>
        <color>7f00ff00</color>
        <width>4</width>
      </LineStyle>
      <PolyStyle>
        <color>7f00ff00</color>
      </PolyStyle>
    </Style>
    <Placemark>
      <name>'.$shortname.'</name>
      <description>'.$description.'</description>
      <styleUrl>#greenLineGreenPoly</styleUrl>
      <LineString>
        <extrude>1</extrude>
        <tessellate>1</tessellate>
        <altitudeMode>absolute</altitudeMode>
	<coordinates>
	'
					       );
					
					//设置开始和结束行
					$start = ($startline >= 0) ? $startline : 0;
					$end = ($endline >= 0) ? $endline : count($data)-1;
					
					//设置最高时速，总时速，时速数据条数
					$max_spd = 0;
					$total_spd = 0;
					$spd_num = 0;
					
					//设置最高海拔，最低海拔，总海拔，海拔数据条数
					$max_alt = -9999;
					$min_alt = 8849;
					$total_alt = 0;
					$alt_num = 0;
					
					//设置最高踏频，总踏频，踏频记录条数
					//.....
					
					//设置最大最小经纬度。
					
					$min_lat = (float) 500;
					$max_lat = (float) -500;
					$min_lon = (float) 500;
					$max_lon = (float) -500;
					
					//设置总距离
					$distance = (float) 0;
					if (isset($data[$start][4]) && isset($data[$start][3])){
						$old_lat = $data[$start][3];
						$old_lon = $data[$start][4];
					}
					else
					{
						$old_lat = 0;
						$old_lon = 0;
					}
					
					//图表数据初始化
					$speed_chart = array();
					$alt_chart = array();
					$sat_chart = array();
					$links = array();
					
					//生成KML数据段
					for ($count = $start; $count <= $end; $count++)
					{
						if (isset($data[$count][4]) && isset($data[$count][3]) && isset($data[$count][5])
						    && $data[$count][4] && $data[$count][3] && $data[$count][5])
						{
							//计算总距离
							if ($count > $start) //第2个坐标点开始计算
							{
								$distance += $this->_get_distance($data[$count][3], $data[$count][4], $old_lat, $old_lon);
								$old_lat = $data[$count][3];
								$old_lon = $data[$count][4];
							}

							//天朝坐标纠偏
							$pos = $this->gps->get_offsets($data[$count][3],$data[$count][4],1);
							$data[$count][3] = ((string) $pos[0]). substr($data[$count][3],strlen($pos[0]));
							$data[$count][4] = ((string) $pos[1]). substr($data[$count][4],strlen($pos[1]));
							fwrite($kf,$data[$count][4].",".$data[$count][3].",".$data[$count][5]."\n");
							
							//记录最大最小经纬度
							if ($data[$count][3] < $min_lat) $min_lat = $data[$count][3];
							if ($data[$count][3] > $max_lat) $max_lat = $data[$count][3];
							if ($data[$count][4] < $min_lon) $min_lon = $data[$count][4];
							if ($data[$count][4] > $max_lon) $max_lon = $data[$count][4];
							
						}

						//SVG图形数据
						if (isset($data[$count][0]) && isset($data[$count][1]) && isset($data[$count][2]) && isset($data[$count][3]) && isset($data[$count][4]) && isset($data[$count][5]) && isset($data[$count][6]))
						{
							$timeStr = @date("H:i:s",@strtotime($data[$count][0]." ".$data[$count][1])+TIME_OFFSET);
							$speed_chart[$timeStr] = $data[$count][6];
							$alt_chart[$timeStr] = $data[$count][5];
							$sat_chart[$timeStr] = $data[$count][2];
							$links[$timeStr] = "javascript:window.parent.setIcon(".$data[$count][3].",".$data[$count][4].");";
							
							//时速数据统计
							if ($data[$count][6] > $max_spd) $max_spd = $data[$count][6];
							if ($data[$count][6] > 0)
							{
								$total_spd += $data[$count][6];
								$spd_num ++;
							}
							
							//高度数据统计
							if ($data[$count][5] > $max_alt) $max_alt = $data[$count][5];
							if ($data[$count][5] < $min_alt) $min_alt = $data[$count][5];
							$total_alt += $data[$count][5];
							$alt_num ++;
							
							//踏频数据统计
							//....
						}

					}
					
					fwrite($kf,
					       '
	</coordinates>
      </LineString>
    </Placemark>
	<Placemark>
		<name>起点</name>
		<description>'.@date('Y-m-d H:i:s', @strtotime($data[$start][0].' '.$data[$start][1]) + TIME_OFFSET).'</description>
		<Point>
		<coordinates>'.$data[$start][4].','.$data[$start][3].',0</coordinates>
		</Point>
	</Placemark>
	<Placemark>
		<name>终点</name>
		<description>'.@date('Y-m-d H:i:s', @strtotime($data[$end][0].' '.$data[$end][1]) + TIME_OFFSET).'</description>
		<Point>
		<coordinates>'.$data[$end][4].','.$data[$end][3].',0</coordinates>
		</Point>
	</Placemark>
 
  </Document>
</kml>'
					       );
					fclose($kf);
					
					$svgname = str_replace('//','/', $this->_build_path($sm->user['uid'], $gen_time, 'svg'))."/".$kfn;
					
					if(is_array($speed_chart)) $this->_SVG($svgname."_spd.svg", $speed_chart, array(array('red', 'yellow')), $links);
					if(is_array($alt_chart)) $this->_SVG($svgname."_alt.svg", $alt_chart, array(array('blue', 'white')), $links);
					if(is_array($sat_chart)) $this->_SVG($svgname."_sat.svg", $sat_chart, array(array('green', 'yellow')), $links, 640, 200);
					
					
					$starttime = @strtotime($data[$start][0].' '.$data[$start][1]);
					$endtime = @strtotime($data[$end][0].' '.$data[$end][1]);
					$lat_scale = $min_lat.",".$max_lat;
					$lon_scale = $min_lon.",".$max_lon;
					
					//新增数据库记录
					$res = $this->Gps_log_files->insert_file(array(
						'uid' => $sm->user['uid'],
						'sid' => $sid,
						'log_time' => $starttime,
						'gen_time' => $gen_time,
						'filename' => $kfn,
						'shortname' =>$shortname,
						'description' => $description,
						'start' => $starttime,
						'end' => $endtime,
						'lat_scale' => $lat_scale,
						'lon_scale' => $lon_scale,
						'distance' => $distance,
						'gen_date' => floor($starttime / 86400)*86400,
						'max_spd' => $max_spd,
						'avg_spd' => $total_spd/$spd_num,
						'max_alt' => $max_alt,
						'min_alt' => $min_alt,
						'avg_alt' => $total_alt/$alt_num
						)
					);
					if ($res)
					{
						$this->Gps_log_source->add_remove_tracks($sm->user["uid"], $sid);
						echo '<div class="info">数据分析完成，轨迹成功绘制。跳转观看结果。</div><script language="javascript">window.location="'.site_url().'/view/index/'.$res.'";</script>';	
					}
				}
			}
		}
	}
	
	function _SVG($filename, $values, $colours, $links=NULL, $w=640, $h=400)
	{
		$settings = array(
		  'back_colour' => '#eee',  'stroke_colour' => '#000',
		  'back_stroke_width' => 0, 'back_stroke_colour' => '#eee',
		  //'back_image' => 'images/svgbg.png',
		  'axis_colour' => '#333',  'axis_overlap' => 2,
		  'axis_font' => 'Georgia', 'axis_font_size' => 10,
		  'grid_colour' => '#666',  'label_colour' => '#000',
		  'pad_right' => 20,        'pad_left' => 20,
		  'link_base' => '',       'link_target' => '',
		  'fill_under' => true,
		  'fill_opacity' => 0.7,
		  'marker_size' => 3,
		  'marker_type' => 'circle',
		  'marker_colour' => 'blue'
		);

		//$colours = array(array('red','yellow'), array('blue','white'));
		//$links = array('Dough' => 'jpegsaver.php', 'Ray' => 'crcdropper.php','Me' => 'svggraph.php');
					
		$this->load->library('SVGGraph/SVGGraph.php');
					
		$graph = $this->svggraph;
		$graph->Init($w, $h, $settings);
					
		$graph->colours = $colours;
					 
		$graph->Values($values);
		$graph->Links($links);
		$graph->Save('LineGraph', $filename);		
	}

	function _build_path($uid,$timestamp,$type){
		$dirs = array(
			$uid,
			$type,
			@date("Y", $timestamp),
			@date("m", $timestamp),
			@date("d", $timestamp)
		);
		
		$path = base_dir().STORAGE_PATH;
		foreach ($dirs as $dir){
			$path .="/".$dir;
			if (!is_dir($path)) {
				mkdir($path);
			}
		}
				
		return $path;
	}
	function _get_distance($lat1, $lng1, $lat2, $lng2){ 
		$radLat1 = $lat1 * (PI / 180);
		$radLat2 = $lat2 * (PI / 180);
		
		$a = $radLat1 - $radLat2; 
		$b = ($lng1 * (PI / 180)) - ($lng2 * (PI / 180)); 
		
		$s = 2 * asin(sqrt(pow(sin($a/2),2) + cos($radLat1)*cos($radLat2)*pow(sin($b/2),2))); 
		$s = $s * EARTH_RADIUS; 
		$s = round($s * 10000) / 10000; 
		return $s; 
	}
	
}
?>